package service

import (
	"errors"
	"fmt"
	"go-admin-server/app/dao"
	"go-admin-server/app/dao/model"
	"go-admin-server/app/dao/repository"
	"go-admin-server/common/base"
	"golang.org/x/crypto/bcrypt"
)

var UserService = new(userService)

type userService struct{}

func (a *userService) Create(userDto *model.User) error {
	password, err := bcrypt.GenerateFromPassword([]byte(userDto.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	userDto.Password = string(password)
	return repository.UserRepo.Create(userDto)
}

func (a *userService) Update(userDto *model.User) error {
	err := dao.DB.Model(&model.User{}).Where("id = ?", userDto.ID).Updates(userDto).Error
	if err != nil {
		return err
	}
	return nil
}

func (a *userService) Delete(ids *[]int) error {
	err := dao.DB.Debug().Delete(&model.User{}, ids).Error
	return err
}

func (a *userService) Validate(userDto *model.User) error {
	if userDto == nil {
		return errors.New("user is empty")
	}
	if userDto.UserName == "" {
		return errors.New("user name is empty")
	}
	if len(userDto.Password) < base.MinPasswordLength {
		return fmt.Errorf("password length must great than %d", base.MinPasswordLength)
	}
	return nil
}
